package factorytest.iflytek.com.einkiflytekfactorytest.common;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import android.os.Build;
import android.os.Environment;
import android.provider.Settings;

import java.io.File;

import factorytest.iflytek.com.einkiflytekfactorytest.BuildConfig;
import factorytest.iflytek.com.einkiflytekfactorytest.CpuTestActivity;
import factorytest.iflytek.com.einkiflytekfactorytest.FTFloatWindowService;
import factorytest.iflytek.com.einkiflytekfactorytest.agingtest.AgingTestItemAttr;
import factorytest.iflytek.com.einkiflytekfactorytest.config.EinkProperty;
import factorytest.iflytek.com.einkiflytekfactorytest.config.OTATestConfig;
import factorytest.iflytek.com.einkiflytekfactorytest.device.DeviceAttr;
import factorytest.iflytek.com.einkiflytekfactorytest.engineerui.EngineerTestItemsEnum;
import factorytest.iflytek.com.einkiflytekfactorytest.MainActivity;
import factorytest.iflytek.com.einkiflytekfactorytest.R;
import factorytest.iflytek.com.einkiflytekfactorytest.factorytestui.FactoryBluetoothActivity;
import factorytest.iflytek.com.einkiflytekfactorytest.factorytestui.FactoryPCBAActivity;
import factorytest.iflytek.com.einkiflytekfactorytest.factorytestui.FactoryTestItemsEnum;
import factorytest.iflytek.com.einkiflytekfactorytest.utils.TimeStringUtils;


/**
 * Created by sst on 2018/9/6.
 */

public class FTUtils {

    private static final String FT_PATH = Environment.getExternalStorageDirectory().getPath() + File.separator + "htfyunFT";

    public static String getFTStorageDirectory() {

        File file = new File(FT_PATH);
        if (!file.exists()) {
            file.mkdirs();
        }

        return file.getAbsolutePath();
    }

    public static String getAgingResultInfo(Context context) {
        StringBuilder sb = new StringBuilder();
        String title = context.getString(R.string.aging_result_info);
        sb.append(title);

        String useTime = TimeStringUtils.makeTimeString(AgingTestItemAttr.getAgingTimeTick_ms(context));

        String useTimeAbsolute = TimeStringUtils.makeTimeString(
                (AgingTestItemAttr.getAgingExitTimeAbsolute_ms(context) - AgingTestItemAttr.getAgingStartTimeAbsolute_ms(context)));

        sb.append(context.getString(R.string.aging_result_use_time, useTime, useTimeAbsolute));


        String emmcCpuUseTime = TimeStringUtils.makeTimeString(
                (AgingTestItemAttr.emmc_cpu.getExitTime_ms(context) - AgingTestItemAttr.emmc_cpu.getStartTime_ms(context)));
        String emmcCpuUseTimeAbsolute = TimeStringUtils.makeTimeString(
                (AgingTestItemAttr.emmc_cpu.getExitTimeAbsolute_ms(context) - AgingTestItemAttr.emmc_cpu.getStartTimeAbsolute_ms(context)));

        String emmcCpuTitle = context.getString(R.string.aging_result_emmc_cpu, emmcCpuUseTime, emmcCpuUseTimeAbsolute);
        String pass = context.getString(R.string.test_result_pass);
        String fail = context.getString(R.string.test_result_fail);
        String result = context.getString(R.string.test_result_unknown);
        if ((AgingTestItemAttr.emmc_cpu.getExitTime_ms(context) - AgingTestItemAttr.emmc_cpu.getStartTime_ms(context)) > 60 * 100) {
            if (AgingTestItemAttr.isEmmcCpuTestOK(context)) {
                result = pass;
            } else {
                result = fail + "," + AgingTestItemAttr.getLogForEmmcCpuTestFailed(context);
            }
        }
        String emmcCpuResult = context.getString(R.string.aging_result_emmc_cpu_result, result);
        sb.append(emmcCpuTitle);
        sb.append(emmcCpuResult);


        final long rebootStartTime = AgingTestItemAttr.reboot.getStartTime_ms(context);
        final long rebootExitTime = AgingTestItemAttr.reboot.getExitTime_ms(context);
        String rebootUseTime = TimeStringUtils.makeTimeString( (rebootExitTime - rebootStartTime));
        String rebootUseTimeAbsolute = TimeStringUtils.makeTimeString(
                (AgingTestItemAttr.reboot.getExitTimeAbsolute_ms(context) - AgingTestItemAttr.reboot.getStartTimeAbsolute_ms(context)));

        String rebootTitle = context.getString(R.string.aging_result_reboot, rebootUseTime, rebootUseTimeAbsolute);
        String rebootCount = context.getString(R.string.aging_result_reboot_count, AgingTestItemAttr.reboot.getTestCount(context));
        sb.append(rebootTitle);
        sb.append(rebootCount);

        final long sleepStartTime = AgingTestItemAttr.sleep.getStartTime_ms(context);
        final long sleepExitTime = AgingTestItemAttr.sleep.getExitTime_ms(context);
        String sleepUseTime = TimeStringUtils.makeTimeString( (sleepExitTime - sleepStartTime));
        String sleepUseTimeAbsolute = TimeStringUtils.makeTimeString(
                (AgingTestItemAttr.sleep.getExitTimeAbsolute_ms(context) - AgingTestItemAttr.sleep.getStartTimeAbsolute_ms(context)));

        String sleepTitle = context.getString(R.string.aging_result_sleep, sleepUseTime, sleepUseTimeAbsolute);
        String sleepCount = context.getString(R.string.aging_result_sleep_count, AgingTestItemAttr.sleep.getTestCount(context));
        sb.append(sleepTitle);
        sb.append(sleepCount);

        final long hardwareStartTime = AgingTestItemAttr.hardware.getStartTime_ms(context);
        final long hardwareExitTime = AgingTestItemAttr.hardware.getExitTime_ms(context);
        String hardwareUseTime = TimeStringUtils.makeTimeString( (hardwareExitTime - hardwareStartTime));
        String hardwareUseTimeAbsolute = TimeStringUtils.makeTimeString(
                (AgingTestItemAttr.hardware.getExitTimeAbsolute_ms(context) - AgingTestItemAttr.hardware.getStartTimeAbsolute_ms(context)));

        String hardwareTitle = context.getString(R.string.aging_result_hardware, hardwareUseTime, hardwareUseTimeAbsolute);
        String screenCount = context.getString(R.string.aging_result_hardware_screen_count, AgingTestItemAttr.getHardwareScreenCount(context));
        String playCount = context.getString(R.string.aging_result_hardware_play_count, AgingTestItemAttr.getHardwarePlaySoundCount(context));
        String recordCount = context.getString(R.string.aging_result_hardware_record_count, AgingTestItemAttr.getHardwareRecordCount(context));
        String wifiCount = context.getString(R.string.aging_result_hardware_wifi_count, AgingTestItemAttr.getHardwareWifiOnOffCount(context));
        String btCount = context.getString(R.string.aging_result_hardware_bt_count, AgingTestItemAttr.getHardwareBTOnOffCount(context));
        String ledCount = context.getString(R.string.aging_result_hardware_led_count, AgingTestItemAttr.getHardwareLedCount(context));

        int cpuTestCount = AgingTestItemAttr.getHardwareCpuTestCount(context);
        int cpuTestFailCount = AgingTestItemAttr.getHardwareCpuFailCount(context);

        String cpuState = context.getString(R.string.aging_result_hardware_cpu_test, cpuTestCount, cpuTestFailCount);
        String errorBootState = context.getString(R.string.aging_result_hardware_error_boot, EinkProperty.getErrorBootCount());

        sb.append(hardwareTitle);
        sb.append(screenCount);
        sb.append(playCount);
        sb.append(recordCount);
        sb.append(wifiCount);
        sb.append(btCount);
        sb.append(ledCount);
        sb.append(cpuState);
        sb.append(errorBootState);

        if (AgingTestItemAttr.isHardwareEmmcTestFailed(context)) {

            String emmcFail = context.getString(R.string.aging_result_hardware_emmc_faild, AgingTestItemAttr.PATH_TEST_EMMC_HARDWARE_FAIL);
            sb.append(emmcFail);

        } else {
            String emmcCount = context.getString(R.string.aging_result_hardware_emmc_count, AgingTestItemAttr.getHardwareEmmcCount(context));
            sb.append(emmcCount);
        }

        return sb.toString();
    }

    public static boolean isFTPassed() {
        return isEngineerFTPassed() || isFactoryFTPassed();
    }

    /////////////////////////////////

    private static boolean isEngineerFTPassed() {

        return isEngineerTestItemsAfterAgingAllPassed() && isEngineerTestItemsAllPassed();
    }

    public static boolean isEngineerTestItemsAllPassed() {
        boolean allOk = true;
        for (EngineerTestItemsEnum item : EngineerTestItemsEnum.values()) {
            if (!item.isPassed(null)) {
                allOk = false;
                break;
            }
        }

        return allOk;

    }

    public static boolean isEngineerTestItemsAllPassedExcludeAging() {
        boolean allOk = true;
        for (EngineerTestItemsEnum item : EngineerTestItemsEnum.values()) {
            if (item != EngineerTestItemsEnum.aging && !item.isPassed(null)) {
                allOk = false;
                break;
            }
        }
        return allOk;
    }

    private static boolean isEngineerTestItemsAfterAgingAllPassed() {
        boolean allOk = true;
        for (EngineerTestItemsEnum item : EngineerTestItemsEnum.values()) {
            if (!item.isPassedForAfterAging(null)) {
                allOk = false;
                break;
            }
        }

        return allOk;

    }

    //////////////////////////////////////////////////////////
    /////////////////////////////////////////////////////////
    private static boolean isFactoryFTPassed() {

        return isFactoryTestItemsAfterAgingAllPassed() && isFactoryTestItemsAllPassed();
    }

    public static boolean isFactoryTestItemsAllPassedExcludeNoActivity() {
        boolean allOk = true;
        for (FactoryTestItemsEnum item : FactoryTestItemsEnum.values()) {
            if (item == FactoryTestItemsEnum.bluetooth && !DeviceAttr.getRunningDeviceAttr().hasBluetooth()) {
                continue;
            }
            if (!item.isPassed(null) && item.getItemClass() != null) {
                allOk = false;
                break;
            }
        }

        return allOk;

    }

    public static boolean isFactoryTestItemsAllPassed() {
        boolean allOk = true;
        for (FactoryTestItemsEnum item : FactoryTestItemsEnum.values()) {
            if (item == FactoryTestItemsEnum.bluetooth && !DeviceAttr.getRunningDeviceAttr().hasBluetooth()) {
                continue;
            }
            if (!item.isPassed(null)) {
                allOk = false;
                break;
            }
        }

        return allOk;

    }

    public static boolean isFactoryTestItemsAllPassedExcludeAging() {
        boolean allOk = true;
        for (FactoryTestItemsEnum item : FactoryTestItemsEnum.values()) {
            if (item == FactoryTestItemsEnum.bluetooth && !DeviceAttr.getRunningDeviceAttr().hasBluetooth()) {
                continue;
            }
            if (item.getItemClass() != null && item != FactoryTestItemsEnum.aging && !item.isPassed(null)) {
                allOk = false;
                break;
            }
        }
        return allOk;
    }

    private static boolean isFactoryTestItemsAfterAgingAllPassed() {
        boolean allOk = true;
        for (FactoryTestItemsEnum item : FactoryTestItemsEnum.values()) {
            if (item == FactoryTestItemsEnum.bluetooth && !DeviceAttr.getRunningDeviceAttr().hasBluetooth()) {
                continue;
            }
            if (!item.isPassedForAfterAging(null)) {
                allOk = false;
                break;
            }
        }

        return allOk;
    }

    public static void clearAgingResult(Context context) {

        String fail = context.getString(R.string.test_result_fail);

        EngineerTestItemsEnum aging = EngineerTestItemsEnum.aging;

        aging.setResult(context, fail);
        if (aging.isKeepTestAfterAging()) {
            aging.setResultForAfterAging(context, fail);
        }

        FactoryTestItemsEnum factoryAging = FactoryTestItemsEnum.aging;

        factoryAging.setResult(context, fail);
        if (factoryAging.isKeepTestAfterAging()) {
            factoryAging.setResultForAfterAging(context, fail);
        }


        for (AgingTestItemAttr itemAttr : AgingTestItemAttr.values()) {
            itemAttr.clearAll(context);
        }

        AgingTestItemAttr.clearAgingAll(context);

        OTATestConfig.setEssentialForOTATest(context, false);
    }

    //////////////////////////////////////////
    public static void startFTFloat(Context context) {

        boolean canStartOverlays = true;
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M && !BuildConfig.CanDrawOverlays) {
            if(!Settings.canDrawOverlays(context.getApplicationContext())) {
                //启动Activity让用户授权

                canStartOverlays = false;

                Intent it = new Intent(Settings.ACTION_MANAGE_OVERLAY_PERMISSION);
                it.setData(Uri.parse("package:" + context.getPackageName()));
                context.startActivity(it);
            }
        }

        if (canStartOverlays) {
            context.getApplicationContext().startService(new Intent(context.getApplicationContext(), FTFloatWindowService.class));
        }
    }

    public static void stopFTFloat(Context context) {
        context.getApplicationContext().stopService(new Intent(context.getApplicationContext(), FTFloatWindowService.class));
    }

    public static void startMainActivity(Context context) {
        FTUtils.startActivity(context, MainActivity.class);
    }

    public static void startPCBAMainActivity(Context context) {
        FTUtils.startActivity(context, FactoryPCBAActivity.class);
    }

    public static void startActivity(Context context, Class<? extends Activity> cls) {
        Intent intent = new Intent(context, cls);
        intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        context.startActivity(intent);
    }

    public static boolean isInAgingTest(Context context) {
        return AgingTestItemAttr.isAgingTestEnabled(context);
    }
}
